package com.chinackts.auth.repository.redis;

import com.alibaba.fastjson.JSON;
import com.chinackts.auth.model.CookieStore;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Repository;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author Lianhong
 * @since 2021/10/27
 */
@Repository
public class CookieStoreRepository {

    @Resource
    private StringRedisTemplate redisTemplate1;

    private static final String KEY = "%s:cookie";

    @Value("${e-port.redis.timeout}")
    private long timeout;

    /**
     * 获取cookie
     *
     * @param id 用户标识
     */
    public List<CookieStore> getCookies(String id) {
        HashOperations<String, String, String> ops = this.redisTemplate1.opsForHash();
        List<String> cookies = ops.values(String.format(KEY, id));
        return CollectionUtils.isEmpty(cookies) ? new ArrayList<>() : JSON.parseArray(cookies.toString(), CookieStore.class);
    }

    /**
     * 存储cookie
     *
     * @param id 用户标识
     */
    public void saveCookies(String id, List<CookieStore> cookies) {
        HashOperations<String, String, String> ops = this.redisTemplate1.opsForHash();
        Map<String, String> cookieMap = new HashMap<>();
        for (CookieStore c : cookies) {
            cookieMap.put(c.getName(), JSON.toJSONString(c));
        }
        ops.putAll(String.format(KEY, id), cookieMap);
    }

    /**
     * 设置cookie到期时间
     *
     * @param id 用户标识
     */
    public void expire(String id) {
        this.redisTemplate1.expire(String.format(KEY, id), timeout, TimeUnit.HOURS);
    }
}
